﻿
/*
 *mysql.cpp
 *说明：封装的SQL连接
*/
#include <QtSql>
#include <QSqlDatabase>
#include <QDebug>
#include "mysql.h"

MySql::MySql(QObject *parent)
    :QObject(parent)
{
    dbDriver="QMYSQL";
    dbName="mydata";
    userName="root";
    userPwd="zkzl1-1=mysql";
    hostName="localhost";
    hostPort=3306;
    db=connectDB();
}
//连接数据库
QSqlDatabase MySql::connectDB()
{
    QSqlDatabase db = QSqlDatabase::addDatabase(dbDriver);//添加驱动
    db.setHostName(hostName); //设置主机名
    db.setDatabaseName(dbName); //设置数据库名
    db.setUserName(userName); //设置用户名
    db.setPassword(userPwd); //设置用户密码
    db.setPort(hostPort);//设置端口号

    if(!db.open())
    {
        qDebug() << "Failed to connect to mysql";
        QMessageBox::warning(0,"错误",db.lastError().text());
    }
    else
    {
        qDebug() << "success to connect to mysql";
    }

    return db;
}

// 数据库命令执行
ExecuteResults MySql::DbExecute(QSqlDatabase db, QString str)
{
    ExecuteResults *execResults = new ExecuteResults();
    QSqlQuery query(db);
    bool flag = query.exec(str);
    execResults->flag = flag;
    execResults->query = query;
    return *execResults;
}
